<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :title="pagetitle"
      :visible="showadd"
      @close="cancel"
    >
      <el-form ref="myform" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" placeholder="请选择">
            <el-option
              v-for="(item, index) in userList"
              :key="index"
              :label="item.username"
              :value="item.username"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="sumbit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartmentsApi,
  getDepartmentsListApi,
  addDepartmentsApi,
  getDepartmentsByIdApi,
  EditDepartmentsByIdApi
} from '@/api/departments.js'
export default {
  props: ['showadd', 'currentObj'],
  data () {
    return {
      //表单属性
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 定义校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          {
            validator: async (rule, value, callback) => {
              const res = await getDepartmentsApi()
              if (!this.form.id) {
                //新增验证规则
                res.data.depts.some(
                  item => item.name === value && item.pid === this.currentObj.id
                )
                  ? callback(new Error('部门名称不能重复'))
                  : callback()
              } else {
                //编辑验证规则
                res.data.depts.some(
                  item =>
                    item.name === value &&
                    item.pid === this.currentObj.pid &&
                    item.id !== this.form.id
                )
                  ? callback(new Error('部门名称不能重复'))
                  : callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          {
            validator: async (rule, value, callback) => {
              const res = await getDepartmentsApi()
              if (!this.form.id) {
                //新增验证规则
                res.data.depts.some(item => item.code === value)
                  ? callback(new Error('部门编码不能重复'))
                  : callback()
              } else {
                //编辑验证规则
                res.data.depts.some(
                  item => item.code === value && item.id !== this.form.id
                )
                  ? callback(new Error('部门编码不能重复'))
                  : callback()
              }
            },
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-50个字符',
            trigger: 'blur'
          }
        ]
      },
      userList: []
    }
  },
  computed: {
    pagetitle: function () {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    async getheadId (id) {
      const res = await getDepartmentsByIdApi(id)
      this.form = res.data
    },
    //取消按钮
    cancel () {
      // 关闭时，最好清除面板中的数据
      this.form = {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门 ID
      }
      // 重置校验
      this.$refs.myform.resetFields()
      this.$emit('update:showadd', false)
    },
    //
    async gethead () {
      const res = await getDepartmentsListApi()
      console.log(res)
      this.userList = res.data
    },
    //确定按钮
    sumbit () {
      this.$refs.myform.validate(async val => {
        if (val) {
          if (!this.form.id) {
            await addDepartmentsApi({
              ...this.form,
              pid:this.currentObj.pid==='-1'?'':this.currentObj.id
            })
          } else {
            await EditDepartmentsByIdApi(this.form)
          }
          this.$emit('update:showadd', false)
          this.$message.success(this.form.id?'编辑成功':'新增成功')
          this.$emit('updateList')
          this.form = {
            name: '',
            code: '',
            manager: '',
            introduce: ''
          }
        } else {
          console.log('新增失败')
        }
      })
    }
  },
  created () {
    this.gethead()
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
